import styles from '../styles.less';
import { Dropdown, Image, Modal, Pagination, Space, Table, Tag } from 'antd';
import { useCallback, useEffect } from 'react';
import Opera from './Opera';
import { connect, useAccess } from 'umi';
import { DownOutlined, ExclamationCircleFilled } from '@ant-design/icons';

const DataTable = (props) => {

  const { dispatch, dataTable, submitting, loading } = props;
  const { setOrders, setUsers, setSalers, setSalersSetting, setDataForm, tablePayload, setTablePayload } = props.data;
  const access = useAccess();

  /* 获取列表 */
  const fetchList = useCallback((payload) => {
    dispatch({
      type: 'POperationCampain/fetchList',
      payload: payload,
    });
  }, [dispatch]);

  /* 查询监听 */
  useEffect(() => {
    fetchList(tablePayload);
  }, [fetchList, tablePayload]);

  /* 编辑 */
  function edit(e, record) {
    e.preventDefault();
    setDataForm({
      visible: true,
      title: '编辑操作',
      data: record,
    });
    return false;
  }

  /* 删除 */
  function del(e, record) {
    e.preventDefault();
    if (!submitting) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled />,
        content: '是否确定删除数据？',
        onOk() {
          dispatch({
            type: 'POperationCampain/del',
            payload: [record.id],
            callback: () => {
              setTablePayload({ ...tablePayload, pageNum: 1 });
            },
          });
        },
      });
    }
    return false;
  }

  /* 分销员设置 */
  function salersSetting(record) {
    setSalersSetting({
      visible: true,
      title: '分销员设置',
      data: record,
    });
  }

  /* 客户列表 */
  function users(record) {
    setUsers({
      visible: true,
      title: '客户列表',
      data: record,
    });
  }

  /* 订单列表 */
  function orders(record) {
    setOrders({
      visible: true,
      title: '订单列表',
      data: record,
    });
  }

  const columns = [
    {
      title: '序号',
      width: 70,
      align: 'center',
      fixed: 'left',
      render: ({}, {}, index) => (
        <span>
          {(tablePayload.pageNum - 1) * tablePayload.pageSize + index + 1}
        </span>
      ),
    },
    {
      title: '封面图',
      dataIndex: 'cover',
      align: 'center',
      width: 100,
      render: (_, record) => {
        return (
          <Image
            width={40} height={40} src={record.cover}
            fallback=""
          />
        );
      },
    },
    {
      title: '活动名称',
      dataIndex: 'name',
      align: 'center',
      width: 240,
      ellipsis: true,
    },
    {
      title: '活动时间',
      dataIndex: 'timeStart',
      align: 'center',
      width: 220,
      ellipsis: true,
      render: (_, record) => {
        return (
          <span>{record.timeStart ? `${record.timeStart.substring(0, 10)}至${record.timeEnd.substring(0, 10)}` : '-'}</span>
        );
      },
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      align: 'center',
      width: 140,
      ellipsis: true,
      render: (_, record) => {
        return (
          <Tag color={record.status === 1 ? 'geekblue' : 'volcano'}>
            {record.status === 1 ? '正常' : '停用'}
          </Tag>
        );
      },
    },
    {
      title: '关联类型',
      dataIndex: 'aboutType',
      align: 'center',
      width: 140,
      ellipsis: true,
      render: (_, record) => {
        let text = '-';
        if (record.aboutType === 0) {
          text = '商品';
        }
        if (record.aboutType === 1) {
          text = '服务';
        }
        if (record.aboutType === 2) {
          text = '套餐';
        }
        return (
          <span>{text}</span>
        );
      },
    },
    {
      title: '推广类型',
      dataIndex: 'pubState',
      align: 'center',
      width: 140,
      ellipsis: true,
      render: (_, record) => {
        return (
          <span>{record.pubState === 1 ? '通用推广' : '渠道推广'}</span>
        );
      },
    },
    {
      title: '排序属性',
      dataIndex: 'orderby',
      align: 'center',
      width: 140,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      width: 160,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      align: 'center',
      width: 160,
      fixed: 'right',
      render: (_, record) => {
        let items = [];
        if (access?.campain_salerLink_list) {
          items = [...items, { key: 'salersSetting', label: '分销员设置', onClick: () => salersSetting(record) }];
        }
        if (access?.campain_userRecord_list) {
          items = [...items, { key: 'users', label: '客户列表', onClick: () => users(record) }];
        }
        if (access?.campain_orderRecord_list) {
          items = [...items, { key: 'orders', label: '订单列表', onClick: () => orders(record) }];
        }

        return (
          <Space size="small">
            {access?.campain_info_edit && (
              <a onClick={e => edit(e, record)}>编辑</a>
            )}
            {access?.campain_info_del && (
              <a onClick={e => del(e, record)}>删除</a>
            )}
            {(items.length > 0) && (
              <Dropdown arrow menu={{ items }}>
                <a onClick={(e) => e.preventDefault()}>
                  更多<DownOutlined />
                </a>
              </Dropdown>
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <>
      <div className={styles.myDataTable}>
        <Opera data={{ setSalers, setDataForm }} />
        <Table
          className={styles.myTable} bordered={false} size={'small'} columns={columns}
          dataSource={dataTable.list} rowKey={'id'}
          pagination={false} scroll={{ y: '100%' }} loading={loading}
        />
      </div>
      <Pagination
        pageSize={tablePayload.pageSize} current={tablePayload.pageNum} total={dataTable.total}
        className={styles.myPagination} size={'default'} hideOnSinglePage={false}
        showTotal={(total) => {
          return `共 ${total} 条记录`;
        }}
        pageSizeOptions={[15, 30, 60, 120]}
        showSizeChanger showQuickJumper={true}
        onChange={(page, pageSize) => {
          setTablePayload({ ...tablePayload, pageNum: page, pageSize: pageSize });
        }}
      />
    </>

  );
};

export default connect(({ loading, POperationCampain }) => {
  return {
    loading: loading.effects['POperationCampain/fetchList'],
    submitting: loading.effects['POperationCampain/del'],
    dataTable: POperationCampain.dataTable,
  };
})(DataTable);
